package com.baselibrary.view;

import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ArticleWebViewClient extends WebViewClient {


    public ArticleWebViewClient(){

    }

    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        //view.getSettings().setBlockNetworkImage(true);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //重置webview中img标签的图片大小
        imgReset(view);
        //view.getSettings().setBlockNetworkImage(false);

    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }


    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     **/
    private void imgReset(WebView view) {




            view.loadUrl("javascript:(function(){" +
                    "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"+
                    "var ps = document.getElementsByTagName('p'); " +
                    "var divs = document.getElementsByTagName('div'); " +

                    "for(var i=0;i<ps.length;i++) {var psOne = ps[i]; psOne.style.width= 'auto'; psOne.style.maxWidth = '100%'; psOne.style.height = 'auto';  }" +
                    "for(var i=0;i<divs.length;i++) {var divsOne = divs[i]; divsOne.style.width= 'auto';  divsOne.style.maxWidth = '100%'; divsOne.style.height = 'auto';  }" +



                    "var objs = document.getElementsByTagName('img'); " +
                    "var imgs=[];for(var i=0;i<objs.length;i++) {imgs.push(objs[i].src.replace('_10_0',''))} " +


                    "for(var i=0;i<objs.length;i++){ var url=objs[i].src; var width = Math.round(document.body.clientWidth *1.5);  url = url.replace('_10_0','_'+width+'_0');  objs[i].src=url; }"+



                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "var img = objs[i]; img._index=i;  img.onclick=function(){var params={index:this._index,imgs:imgs};window.injectedObject.imgClick(JSON.stringify(params));};  " +
                    "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                    "}" +
                    ""+
                    "})()");


    }



    public static String repairContent(String content){
        String patternStr="<img\\s*([^>]*)\\s*style=\\\"(.*?)\\\"\\s*([^>]*)>";
        Pattern pattern = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(content);
        String result = content;
        while(matcher.find()) {
            String src = matcher.group(2);
            result = result.replaceAll(src,"width:100%");
        }

        String patternSrcStr="<img\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>";
        Pattern patternSrc = Pattern.compile(patternSrcStr,Pattern.CASE_INSENSITIVE);
        Matcher matcherSrc = patternSrc.matcher(result);
        while(matcherSrc.find()) {
            String src = matcherSrc.group(2);
            String replaceSrc = "";
            if(src.lastIndexOf(".")>0&&(src.contains("hankeapp.cn")||src.contains("39.107.247.82"))){
                replaceSrc = src.substring(0,src.lastIndexOf("."))+"_10_0"+src.substring(src.lastIndexOf("."));
            }
            result = result.replaceAll(Pattern.quote(src),replaceSrc);
        }


        result = result.replaceAll("</pre>","</div>");
        result = result.replaceAll("<pre","<div");

        String css = "<style type=\"text/css\"> img {" +
                "width:100%;" +//限定图片宽度填充屏幕
                "height:auto;" +//限定图片高度自动
                "}" +
                "p div span {" +
                "overflow: hidden;" +//限定图片宽度填充屏幕
                "width:100%;" +//限定图片宽度填充屏幕
                "word-wrap:break-word;"+//允许自动换行(汉字网页应该不需要这一属性,这个用来强制英文单词换行,类似于word/wps中的西文换行)
                "}" +
                "</style>";
        result = "<html><header>" + css + "</header>" + result + "</html>";

        return result;
    }


}